<!--
 * @Author: your name
 * @Date: 2021-07-23 21:31:35
 * @LastEditTime: 2021-07-24 19:54:48
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \hm-news\src\views\login\index.vue
-->
<template>
  <div class="login">
    <van-nav-bar title="登录" left-arrow @click-left="$router.back()">
      <!-- <template #right>
        <van-icon name="search" size="18" />
      </template> -->
    </van-nav-bar>

    <!--
  登录表单
  点击登录按钮的时候，会触发submit事件
  -->

    <!-- 频繁点击登录按钮会发生多次请求 这样会增加服务端得压力
   可以在点击按钮后禁用按钮 -->
    <van-form @submit="login">
      <van-field
        :required="false"
        :num="1 + 1"
        v-model="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
      />
      <van-field
        v-model="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px;">
        <van-button
          round
          block
          type="info"
          :disabled="isLoad"
          :loading="isLoad"
          loading-text="登录中"
          native-type="submit"
        >
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
// import axios from 'axios'
import { userLogin } from '@/api/user'
import { mapMutations } from 'vuex'
// import axios from 'axios'
export default {
  name: 'Login',
  data() {
    return {
      mobile: '',
      code: '',
      isLoad: false,
      rules: {
        mobile: [
          { required: true, message: '手机号不能为空' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号码格式错误'
          }
        ],
        code: [
          { required: true, message: '验证码不能为空' },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式错误'
          }
        ]
      }
    }
  },

  methods: {
    ...mapMutations('user', ['setToken']),
    async login() {
      this.isLoad = true
      console.log('登录中.....')
      try {
        const res = await userLogin(this.mobile, this.code)
        console.log(res)
        // alert('登录成功')
        // Toast.success('登录成功')
        // 法一
        // this.$store.commit('user/setToken', res.data)
        // 法二
        this.setToken(res.data)
        this.$toast.success('登录成功')
        this.$router.push('/')
      } catch {
        // alert('登录失败')
        this.$toast.fail('登录失败')
      }
      this.isLoad = false
    }
  }
}
</script>

<style lang="less"></style>
